import './index.less'
import {Button, Col, Input, Row, Select, Slider, Space} from "antd";

import {
    CheckOutlined,
    MinusOutlined,
    PieChartFilled,
    PlusOutlined,
    UndoOutlined
} from "@ant-design/icons";
import {getAllData} from "../../api/request.ts";
import useAppState from "../../store";
import {useEffect, useState} from "react";

const ControlPanel = () => {
    const {
        setTestData,
        graphData,
        setSimilarTableData,
        setTriggerType,
        setTensileStrength,
        setYieldStrength,
        setGraphData,
        setTriggerId,
        setSpinning
    } = useAppState();
    const submit = async () => {
        setSpinning(true);
        const {data} = await getAllData({params: formItems}, false,selectedViewValue);
        // 更新状态
        setGraphData({
            nodes: data.nodes,
            edges: data.edges
        });
        setTensileStrength(data.Tensile_Strength);
        setYieldStrength(data.Yield_Strength);
        setSpinning(false);
        setTensileRange([0,0])
        setYieldRange([0,0]);
        setTestData(Math.floor(Math.random() * 5).toString());
    }
    // 定义表单项状态，每个项包含 selectValue 和 inputValue
    const [formItems, setFormItems] = useState([
        {selectValue: undefined, inputValue: ''}
    ]);
    const [options, setOptions] = useState([])

    // 添加新表单项
    const addItem = () => {
        setFormItems([...formItems, {selectValue: undefined, inputValue: ''}]);
    };
    // 删除最后一个表单项
    const removeLastItem = () => {
        if (formItems.length > 1) {
            setFormItems(formItems.slice(0, -1));
        }
    };
    // 处理选择器变化
    const handleSelectChange = (index, value) => {
        const newItems = [...formItems];
        newItems[index].selectValue = value;
        setFormItems(newItems);
    };

    // 处理输入框变化
    const handleInputChange = (index, e) => {
        const newItems = [...formItems];
        newItems[index].inputValue = e.target.value;
        setFormItems(newItems);
    };

    // 定义状态存储滑动条值
    const [tensileRange, setTensileRange] = useState([0, 0]);
    const [yieldRange, setYieldRange] = useState([0, 0]);
    const [tensileStrengthMin, setTensileStrengthMin] = useState(0);
    const [tensileStrengthMax, setTensileStrengthMax] = useState(0);
    const [yieldStrengthMin, setYieldStrengthMin] = useState(0);
    const [yieldStrengthMax, setYieldStrengthMax] = useState(0);

    // 处理 Tensile 滑动条变化
    const handleTensileChange = (newRange) => {
        setTensileRange(newRange);
    };

    // 处理 Yield 滑动条变化
    const handleYieldChange = (newRange) => {
        setYieldRange(newRange);
    };
    const confirmRange = () => {
        const tempNodeData = [];
        graphData.nodes.map(item => {
            if (item.data.Tensile_Strength >= tensileRange[0] && item.data.Tensile_Strength <= tensileRange[1] && item.data.Yield_Strength >= yieldRange[0] && item.data.Yield_Strength <= yieldRange[1]) {
                tempNodeData.push(item.data)
            }
        })
        setSimilarTableData(tempNodeData);
        setTriggerType("selectRange");
        setTriggerId('');
    }
    const tempSelect=()=>{
        const tempNodeData = [];
        graphData.nodes.map(item => {

            if (item.data.Ti !== 0 && item.data.Al !== 0&& item.data.Fe !== 0&&item.data.V !== 0&&item.data.O !== 0) {
                tempNodeData.push(item.data)
            }
        })
        setSimilarTableData(tempNodeData);
        setTriggerType("selectRange");
        setTriggerId('');
    }
    const undoRange=()=>{
        setTensileRange([0, 0]);
        setYieldRange([0, 0]);
        setSimilarTableData([]);
        setTriggerType("undoRange");
        setTriggerId('');
    }
    useEffect(() => {
        if (graphData.nodes.length === 0) return;
        const tensile_strengths = graphData.nodes.map(item => item.data.Tensile_Strength);
        setTensileStrengthMax(Math.ceil(Math.max(...tensile_strengths)));
        setTensileStrengthMin(Math.floor(Math.min(...tensile_strengths)))
        const yield_strengths = graphData.nodes.map(item => item.data.Yield_Strength)
        setYieldStrengthMax(Math.ceil(Math.max(...yield_strengths)));
        setYieldStrengthMin(Math.floor(Math.min(...yield_strengths)));
        const tempData = ["ChemicalFormula", "Tensile_Strength", "Yield_Strength", 'id'];
        const tempOptions = []
        Object.keys(graphData.nodes[0].data).map(item => {
            if (!tempData.includes(item)) {
                tempOptions.push({value: item, label: item})
            }
        });
        setOptions(tempOptions);
    }, [graphData])
    const [selectedViewValue, setSelectedViewValue] = useState('Raw View');
    const selectedViewOptions=[
        { value: 'Raw View', label: 'Raw View' },
        { value: 'Matrix View', label: 'Matrix View' },
    ]
    const handleViewChange =async (value) => {
        setSelectedViewValue(value);
        setTensileRange([0, 0]);
        setYieldRange([0, 0]);
        setTriggerType('');
        setTriggerId('');
        setSimilarTableData([]);
        setSpinning(true);
        const {data} = await getAllData({}, true,value);
        // 更新状态
        setGraphData({
            nodes: data.nodes,
            edges: data.edges
        });
        setTensileStrength(data.Tensile_Strength);
        setYieldStrength(data.Yield_Strength);
        setSpinning(false);
        console.log('Selected:', value);
    };
    return (
        <div className="ControlPanel">
            <div className={"fontStyle"}>
                <PieChartFilled/>
                <span>TAExplorer</span></div>
            <div>
                <hr/>
                <div className={"customParameters"}>
                    <Button type={"primary"} onClick={submit} style={{marginBottom:8,width:"100%"}}>Submit</Button>
                    <div style={{marginBottom: 8}}>Custom Parameters:</div>
                    <Row>
                        {formItems.map((item, index) => (
                            <Space
                                key={index}
                                style={{width: "100%", marginBottom: "8px"}}
                            >
                                <Space.Compact>
                                    <Select
                                        style={{width: '70%'}}
                                        showSearch
                                        placeholder="Select"
                                        value={item.selectValue}
                                        onChange={(value) => handleSelectChange(index, value)}
                                        filterOption={(input, option) =>
                                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                        }
                                        options={options}
                                    />
                                    <Input
                                        style={{width: '30%'}}
                                        value={item.inputValue}
                                        onChange={(e) => handleInputChange(index, e)}
                                    />
                                </Space.Compact>
                            </Space>
                        ))}

                        <Space>
                            <Button
                                type="primary"
                                icon={<PlusOutlined/>}
                                onClick={addItem}
                            >
                            </Button>
                            <Button
                                danger
                                icon={<MinusOutlined/>}
                                onClick={removeLastItem}
                                disabled={formItems.length === 1} // 只剩一个时禁用
                            >
                            </Button>
                        </Space>
                    </Row>
                </div>
                <div className={"property"}>
                    <div style={{marginBottom: 8}}>Tensile_Strength:</div>
                    <Row>
                        <Slider
                            range={{draggableTrack: true}}
                            value={tensileRange}
                            onChange={handleTensileChange}
                            min={tensileStrengthMin}
                            max={tensileStrengthMax}
                            style={{width: '100%'}}
                        />
                    </Row>
                    <div style={{marginBottom: 8}}>Yield_Strength:</div>
                    <Row>
                        <Slider
                            range={{draggableTrack: true}}
                            value={yieldRange}
                            onChange={handleYieldChange}
                            min={yieldStrengthMin}
                            max={yieldStrengthMax}
                            style={{width: '100%'}}
                        />
                    </Row>
                    <Space>
                        <Button
                            type="primary"
                            icon={<CheckOutlined/>}
                            onClick={confirmRange}
                        >
                        </Button>
                        <Button
                            type="primary"
                            icon={<UndoOutlined />}
                            onClick={undoRange}
                        >
                        </Button>
                    </Space>
                </div>
                <div className={"switchView"}>
                    <div style={{marginBottom: 8}}>Switch_View:</div>
                    <Select
                        style={{width: '100%'}}
                        value={selectedViewValue}
                        showSearch
                        placeholder="Select"
                        options={selectedViewOptions}
                        onChange={handleViewChange}
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        } // 自定义搜索逻辑
                    />
                </div>
                {/*<Button*/}
                {/*    type="primary"*/}
                {/*    icon={<CheckOutlined/>}*/}
                {/*    onClick={tempSelect}*/}
                {/*    style={{"marginTop":10}}*/}
                {/*>*/}
                {/*    筛选*/}
                {/*</Button>*/}
            </div>

        </div>
    )
}
export default ControlPanel;
